package com.wutianyi.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;

import org.apache.commons.lang.StringUtils;

public class HtmlUtils {

	public static String getBodyString(String url, String contentEncoding) {
		try {
			URL requestUrl = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) requestUrl
					.openConnection();
			if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
				return StringUtils.EMPTY;
			}

			String encoding = connection.getContentEncoding();
			System.out.println(encoding);
			if (StringUtils.isBlank(encoding)) {
				encoding = contentEncoding;
			}
			InputStream inputStream = connection.getInputStream();

			int l = connection.getContentLength();

			if (l == -1) {
				l = 1024;
			}

			ByteArrayOutputStream baos = new ByteArrayOutputStream(l);
			byte[] buf = new byte[1024];
			int len = 0;
			while ((len = inputStream.read(buf)) != -1) {
				baos.write(buf, 0, len);
			}

			return new String(baos.toByteArray(), encoding);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	public static void main(String[] args) throws UnsupportedEncodingException {
		 System.out.println(getBodyString(
		 "http://blog.sina.com.cn/rss/1307309734.xml",
		 "utf-8"));
//		System.out.println(URLEncoder.encode(
//				"http://blog.sina.com.cn/main/html/alltop_more_new_1.html",
//				"utf-8"));
//		System.out.println(URLDecoder.decode("http%253A%252F%252Fblog.sina.com.cn%252Frss%252F1307273980.xml","utf-8"));
	}
}
